package com.example.form.service.impl;

import com.example.form.common.AppResult;
import com.example.form.common.ResultCode;
import com.example.form.dao.ArticleReplyMapper;
import com.example.form.exception.ApplicationException;
import com.example.form.model.Article;
import com.example.form.model.ArticleReply;
import com.example.form.service.IArticleReplyService;
import com.example.form.service.IArticleService;
import com.example.form.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl  implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;//注入帖子回复表的操作类
    @Resource
    private IArticleService articleService;//注入操作帖子表的类
    @Override
    public void creat(ArticleReply articleReply) {
        /*System.out.println(articleReplyMapper);
        System.out.println(articleReply);*/
        //非空校验
        if(articleReply==null||articleReply.getArticleId()==null
                ||articleReply.getPostUserId()==null
                ||StringUtil.isEmpty(articleReply.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());//参数校验失败异常
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认信息:因为articleReply有一些属性是默认要设置的
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte)0);
        Date date= new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //把帖子的回复数据写入帖子回复表中
        int row=articleReplyMapper.insertSelective(articleReply);//动态插入数据
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED.toString());//打印操作失败异常
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //更新帖子表中的帖子中的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());//从参数中获取对应的帖子的id,然后变动
        //打印日志
        log.info("回复成功 帖子id;"+articleReply.getArticleId()+" 用户id:"+articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //非空校验
        if(articleId==null||articleId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));//抛出资源不存在异常
        }
        //调用dao的查询方法
        List<ArticleReply> articleReplies=articleReplyMapper.selectByArticleId(articleId);
        //返回结果
        return articleReplies;
    }
}
